//index.js
//获取应用实例
const app = getApp()


var ctx = null;// 使用 wx.createContext 获取绘图上下文 context
var painting = false;//是否在绘制中
var selectcolor = '#000';
var canvasw = 0;//画布宽度
var canvash = 0;//画布高度
var lastPoint = { x: undefined, y: undefined };


Page({
  data: {

    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canvasw: 0,
    canvash: 0,
    pencolor: '',
    linewidth: 1,
    isShowcolor: false,
    opentool: false,
    toolbtn: true,
    selectit: 'pencil',
    istool: false,
    iseraser: false,
    lineW: false,
    choosecolor: '',
    colorData: {
      //基础色相，即左侧色盘右上顶点的颜色，由右侧的色相条控制
      hueData: {
        colorStopRed: 255,
        colorStopGreen: 0,
        colorStopBlue: 0,
      },
      //选择点的信息（左侧色盘上的小圆点，即你选择的颜色）
      pickerData: {
        x: 0, //选择点x轴偏移量
        y: 480, //选择点y轴偏移量
        red: 0,
        green: 0,
        blue: 0,
        hex: '#000000'
      },
      //色相控制条的位置
      barY: 0
    },
    rpxRatio: 1 //此值为你的屏幕CSS像素宽度/750，单位rpx实际像素

  },
  //事件处理函数
  bindViewTap: function () {
    // wx.navigateTo({
    //   url: '../logs/logs'
    // })
  },
  clickT: function () {
    // wx.navigateTo({
    //   url: '../mypage/mypage',
    //   success: function (res) { },
    //   fail: function (res) { },
    // })
  },
  onLoad: function () {
    this.startCanvas()


  },
  onShow: function () {


  },

  //初始化函数
  initCanvas: function () {
    ctx = wx.createCanvasContext('paint');

  },
  //画布初始化执行
  startCanvas: function () {
    var that = this
    //创建canvas
    this.initCanvas();
    //获取系统信息
    wx.getSystemInfo({
      success: function (res) {
        // console.log(res)
        // let h = 100
        let h = 200
        if (res.windowHeight - res.windowWidth > 300) {
          h = 300
        }
        if (res.windowHeight - res.windowWidth < 200) {
          h = 150
        }
        let canvasw = res.windowWidth - 0;//设备宽度
        let canvash = canvasw + h;
        that.setData({ canvasw: canvasw });
        that.setData({ canvash: canvash });
        that.setData({ pencolor: '#000' })
        that.setData({ rpxRatio: canvasw / 750 })

      },
      fail: function (res) {
        wx.showToast({
          title: '初始化失败，请重试！',
        })
      },
    })
    ctx.setFillStyle('#fff')
    ctx.fillRect(0, 0, this.data.canvasw, this.data.canvash)

  },
  //画方法
  drawLine: function (color, linewidth, x1, y1, x2, y2) {
    ctx.beginPath()
    ctx.setLineCap('round');
    ctx.setLineJoin('round');
    ctx.setStrokeStyle(color);
    ctx.setLineWidth(linewidth);
    ctx.moveTo(x1, y1)
    ctx.lineTo(x2, y2)
    ctx.stroke();
    ctx.closePath()
    ctx.draw(true);
  },

  //触屏开始
  paintStart: function (e) {
    painting = true;

    let x = e.changedTouches[0].x;
    let y = e.changedTouches[0].y;
    lastPoint = { "x": x, "y": y };

  },
  paintMove: function (e) {

    if (painting) {

      let x = e.changedTouches[0].x;
      let y = e.changedTouches[0].y;
      let newPoint = { "x": x, "y": y }

      this.drawLine(this.data.pencolor, this.data.linewidth, lastPoint.x, lastPoint.y, newPoint.x, newPoint.y)
      lastPoint = newPoint;

    };

  },
  paintEnd: function (e) {
    painting = false;
  },

  //显示工具按钮
  showtool: function () {

    if (this.data.opentool) {
      this.setData({
        opentool: false,
        istool: false,
        lineW:false,
      })
    } else {
      wx.createSelectorQuery().select('#j_page').boundingClientRect(function (rect) {
        // 使页面滚动到底部
        wx.pageScrollTo({
          scrollTop: rect.bottom
        })
      }).exec()
      this.setData({
        opentool: true,
        istool: true,
        lineW: true,
      })
      // console.log(this.data.linewidth)
      let ctxL = wx.createCanvasContext('lineweight');
      this.seeline(ctxL, this.data.linewidth)
    }
  },
  // 线大小预览
  seeline: function (ctxL, lwidth) {
    // ctxL.clearRect(0, 0, 100, 70)
    // ctxL.beginPath()
    ctxL.setLineCap('round')
    ctxL.setLineWidth(lwidth)
    ctxL.moveTo(20, 18)
    ctxL.lineTo(50, 18)
    ctxL.stroke()
    ctxL.draw()
  },
  //线大小
  sliderchange: function (e) {
    this.setData({
      linewidth: e.detail.value,
      lineW: true,
    })
    let ctxL = wx.createCanvasContext('lineweight');
    this.seeline(ctxL, this.data.linewidth)
    //console.log(e.detail.value)
  },
  //点击显颜色选择
  showColor: function () {
    if (this.data.isShowcolor) {
      this.setData({
        isShowcolor: false,
      })
    } else {
      this.setData({
        isShowcolor: true,
      })
    }


  },


  //颜色
  onChangeColor: function (e) {
    // console.log(e)
    if (!this.data.iseraser) {
      this.setData({
        pencolor: e.detail.colorData.pickerData.hex,
      })
    }
    selectcolor = e.detail.colorData.pickerData.hex
    this.setData({
      colorData: e.detail.colorData,
      choosecolor: selectcolor
    })
    // console.log(e.detail.colorData.pickerData.hex)
  },
  // 清空
  clearpaint: function () {
    let that = this
    wx.showModal({
      title: '提示',
      content: '确定清空画板？',
      success(res) {
        if (res.confirm) {
          // console.log('用户点击确定')
          ctx.clearRect(0, 0, that.data.canvasw, that.data.canvash)
          ctx.draw()
          ctx.setFillStyle('#fff')
          ctx.fillRect(0, 0, that.data.canvasw, that.data.canvash)
        } else if (res.cancel) {
          // console.log('用户点击取消')
        }
      }
    })

  },
  //橡皮
  backpaint: function (e) {

    this.setData({
      pencolor: '#fff',
      iseraser: true,
      selectit: e.currentTarget.dataset.choos,
    })
  },
  //笔
  penpaint: function (e) {
    this.setData({
      pencolor: selectcolor,
      iseraser: false,
      selectit: e.currentTarget.dataset.choos,
    })
  },
  //保存图片
  savepaint: function () {
    wx.showModal({
      title: '提示',
      content: '确定保存图片到相册？',
      success:(res)=>{
        if(res.confirm){
        // wx.clearStorage()
        //生成临时图
        wx.canvasToTempFilePath({
          canvasId: 'paint',
          success(res) {
            // console.log(res.tempFilePath)
            //存图到相册
            wx.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,

              success(res) {
                // res.authSetting['scope.writePhotosAlbum']
                // console.log(res)
                wx.showToast({
                  title: '保存成功！',
                })
              },
              fail(res) {
                // console.log(res.authSetting['scope.writePhotosAlbum'])
                // console.log(res)
                if (res.errMsg == "saveImageToPhotosAlbum:fail cancel") {
                  wx.showToast({
                    title: '取消保存！',
                    icon: 'none',
                  })
                } else {
                  wx.showToast({
                    title: '保存失败，请授权！',
                    icon: 'none',
                  })
                }
              }
            })
          },
          fail(res) {
            wx.showToast({
              title: '保存失败！',
              icon: 'none',
            })
          }
          
        })
      }
      }
    })
    
  },
  // 拼接图
  linkpic: function () {
    wx.navigateTo({
      url: '../linkpicpage/linkpicpage',
    })
  },
  // 关于
  aboutbtn: function () {
    wx.navigateTo({
      url: '../about/about',
    })
  },

  onShareAppMessage: function (res) {
    if (res.from === 'menu') {
      // 来自页面内转发按钮
      // console.log(res.target)
    }
    return {
      title: '画板',
      path: '/pages/index/index'
    }
  }

})
